
package com.yonyou.gmmc.service.customer.service;

import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.marketing.common.FrameHttpUtil;
import org.marketing.common.constants.CommonConstant;
import org.marketing.common.constants.ResultMsgConstants;
import org.marketing.common.dms.dto.IfMessage;
import org.marketing.common.dto.MQReceiveResult;
import org.marketing.common.dto.MessageDto;
import org.marketing.common.dto.SendTicket;
import org.marketing.common.dto.carOwner.CarOwnerDto;
import org.marketing.common.dto.customerInfo.CarInfoDto;
import org.marketing.common.dto.customerInfo.CounselorDto;
import org.marketing.common.dto.customerInfo.MemberDto;
import org.marketing.common.dto.leads.InsuranceDto;
import org.marketing.common.event.BizEvent;
import org.marketing.common.event.EventCommitQuesionnaireDTO;
import org.marketing.common.event.EventComplaintDto;
import org.marketing.common.event.EventMaintenanceOrderDTO;
import org.marketing.common.event.EventPointsChangedDTO;
import org.marketing.common.event.EventWechatAttentionDTO;
import org.marketing.common.event.enums.EventConstant;
import org.marketing.common.event.enums.EventConstant.EventBizStep;
import org.marketing.common.event.enums.EventConstant.EventBizType;
import org.marketing.common.exception.ServiceBizException;
import org.marketing.common.util.CheckUtil;
import org.marketing.common.util.CommonUtils;
import org.marketing.common.util.MD5Util;
import org.marketing.common.util.MapConverUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yonyou.gmmc.common.service.BaseService;
import com.yonyou.gmmc.common.service.BaseService.MQChannelType;
import com.yonyou.gmmc.common.sms.SmsHttpClient2;
import com.yonyou.gmmc.service.customer.constant.CustomerInfoConstant;
import com.yonyou.gmmc.service.customer.dao.TmCarInfoMapper;
import com.yonyou.gmmc.service.customer.dao.TmCarOwnerMapper;
import com.yonyou.gmmc.service.customer.dao.TmDealerMapper;
import com.yonyou.gmmc.service.customer.dao.TmOwnerCarRelationMapper;
import com.yonyou.gmmc.service.customer.dao.TmPotentialUserMapper;
import com.yonyou.gmmc.service.customer.dao.TtComplaintMapper;
import com.yonyou.gmmc.service.customer.entity.CarOwnerPO;
import com.yonyou.gmmc.service.customer.entity.PointsChangePO;
import com.yonyou.gmmc.service.customer.entity.PotentialUserPO;
import com.yonyou.gmmc.service.customer.entity.TmCarInfo;
import com.yonyou.gmmc.service.customer.entity.TmDealer;
import com.yonyou.gmmc.service.customer.model.TmCarOwner;
import com.yonyou.gmmc.service.customer.model.TmOwnerCarRelation;
import com.yonyou.gmmc.service.customer.model.TmPotentialUser;
import com.yonyou.gmmc.service.customer.model.TtComplaint;

import net.sf.json.JSONObject;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

/**
 * @author Administrator
 * @date 2017年3月8日
 */

@Transactional
@Service("customerService")
public class CustomerService {

	private Logger logger = Logger.getLogger(CustomerService.class);

	@Autowired
	private TmPotentialUserMapper tmPotentialUserMapper;

	@Autowired
	private BaseService eventService;

	@Autowired
	private CustomerServiceInterface customerServiceInterface;

	@Autowired
	private TmDealerMapper tmDealerMapper;

	@Autowired
	private TtComplaintMapper ttComplaintMapper;

	@Autowired
	private TmCarInfoMapper tmCarInfoMapper;
	@Autowired
	private TmOwnerCarRelationMapper tmOwnerCarRelationMapper;
	@Autowired
	private TmCarOwnerMapper tmCarOwnerMapper;

	@Value("${DCMS-url}")
	private String dcmsUrl;
	@Value("${SMS-pass}")
	private String smsPass;
	@Value("${SMS-key}")
	private String smsKey;
	@Value("${SMS_CDKEY}")
	private String SMS_CDKEY;
	@Value("${SMS_PASS}")
	private String SMS_PASS;
	@Value("${SMS_BASEURL}")
	private String SMS_BASEURL;
	@Value("${SMS_TEMPLATEID_SC}")
	private String SMS_TEMPLATEID_SC;

	@Value("${DEALER-URL}")
	private String dealerUrl;

	@Value("${DEALER_USERS-URL}")
	private String dealerUsersUrl;

	public Map<String, Object> queryFans(String openId) {
		Map<String, Object> resultMap = new HashMap<>();
		resultMap = tmPotentialUserMapper.queryFans(openId);
		logger.info("返回信息为>>>>>>>" + resultMap);
		// if (s == null || s == "") {
		// logger.info("不是会员");
		// resultMap.put("flag", "0");
		// resultMap.put("Message", "不是会员，可以注册");
		// } else {
		// logger.info("是会员");
		// resultMap.put("flag", "1");
		// resultMap.put("Message", "是会员，不可以重复注册！");
		// }
		return resultMap;
	}

	/**
	 * 判断是否为车主
	 * 
	 * @author Administrator
	 * @date 2017年3月18日
	 * @param openId
	 * @return
	 */
	public List<MemberDto> queryUserOwner(String openId) {
		List<MemberDto> dtoList = tmPotentialUserMapper.queryUserOwner(openId);
		return dtoList;
	}
	
	/**
     * 判断是否为车主
     * 
     * @author Administrator
     * @date 2017年3月18日
     * @param openId
     * @return
     * @throws ServiceAppException
     * @throws ServiceBizException
     */
    public List<MemberDto> queryUserOwner2(String openId) {
        List<MemberDto> dtoList = tmPotentialUserMapper.queryUserOwner2(openId);
        return dtoList;
    }

	/**
	 * 会员中心信息查询
	 * 
	 * @author QianKun
	 * @date 2017年2月28日
	 * @param potentialUserId
	 * @return
	 */
	public List<MemberDto> getMemberInfo(String userId) {
		List<MemberDto> dtoList = tmPotentialUserMapper.queryMember(userId);
		if (dtoList.size() == 0) {
			// 没有此人信息
			logger.info("查无此人");
		} else {
			// 判断头像是否有值
			if (dtoList.get(0).getHeadImgurl() == null || dtoList.get(0).getNickName() == null) {
				// 没有头像,更新数据
				String openId = dtoList.get(0).getOpenId();
				String str = customerServiceInterface.getImgurlByOpenId(openId);
				logger.info("Str为：" + str);
				JSONObject jsonObject = JSONObject.fromObject(str);
				String Imgurl = jsonObject.getString("headimgurl");
				String nickName = jsonObject.getString("nickname");
				logger.info("头像为：" + Imgurl);
				// 更新潜客信息
				MemberDto memberDto = new MemberDto();
				memberDto.setOpenId(openId);
				memberDto.setHeadImgurl(Imgurl);
				memberDto.setNickName(nickName);
				logger.info("更新头像");
				tmPotentialUserMapper.updateHeadImgUrl(memberDto);
				dtoList = tmPotentialUserMapper.queryPotential(openId);
			}
		}
		return dtoList;
	}

	/**
	 * 潜客信息查询
	 * 
	 * @author QianKun
	 * @date 2017年3月16日
	 * @param potentialUserId
	 * @return
	 */
	public List<MemberDto> getPotentialInfo(String openId) {
		List<MemberDto> dtoList = tmPotentialUserMapper.queryPotential(openId);
		// 判断头像是否有值
		if (dtoList.size() == 0) {
			// 没有此人信息
			logger.info("查无此人");
		} else {
			if (dtoList.get(0).getHeadImgurl() == null || dtoList.get(0).getNickName() == null) {
				// 没有头像,更新数据
				String str = customerServiceInterface.getImgurlByOpenId(openId);
				logger.info("Str为：" + str);
				JSONObject jsonObject = JSONObject.fromObject(str);
				String Imgurl = jsonObject.getString("headimgurl");
				String nickName = jsonObject.getString("nickname");
				logger.info("头像为：" + Imgurl);
				// 更新潜客信息
				MemberDto memberDto = new MemberDto();
				memberDto.setOpenId(openId);
				memberDto.setHeadImgurl(Imgurl);
				memberDto.setNickName(nickName);
				logger.info("更新头像");
				tmPotentialUserMapper.updateHeadImgUrl(memberDto);
				dtoList = tmPotentialUserMapper.queryPotential(openId);
			}
		}
		return dtoList;
	}

	/**
	 * 更新会员信息(车主)
	 * 
	 * @author QianKun
	 * @date 2017年3月1日
	 * @param memberDto
	 */
	public Map<String, Object> updateCarOwnerInfo(MemberDto memberDto) {
		Map<String, Object> resultMap = new HashMap<>();
		try {
			tmPotentialUserMapper.updateCarOwnerInfo(memberDto);
			resultMap.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_SUCCESS);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			resultMap.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_ERROR);
		}
		return resultMap;
	}

	/**
	 * 更新会员信息(潜客)
	 * 
	 * @author QianKun
	 * @date 2017年3月1日
	 * @param memberDto
	 */
	public Map<String, Object> updatePotentialInfo(MemberDto memberDto, String openId) {
		Map<String, Object> resultMap = new HashMap<String, Object>();

		try {
			memberDto.setOpenId(openId);
			tmPotentialUserMapper.updatePotentialInfo(memberDto);
			resultMap.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_SUCCESS);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			resultMap.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_ERROR);
		}
		return resultMap;
	}

	/**
	 * 更新会员信息(顾问)
	 * 
	 * @author QianKun
	 * @date 2017年3月1日
	 * @param memberDto
	 */
	public Map<String, Object> updateCounselorInfo(MemberDto memberDto, String openId) {
		Map<String, Object> resultMap = new HashMap<>();
		// 查询潜客ID
		Integer PotentialUserId = tmPotentialUserMapper.queryPotentialId(openId);
		memberDto.setPotentialUserId(PotentialUserId);
		try {
			logger.info("查询是否已有顾问");
			String s = tmPotentialUserMapper.selectCounselor(memberDto.getPotentialUserId());
			if (s == null || s == "") {
				logger.info("没有选择过顾问");
				// 新增
				memberDto.setCreateDate(new Date());
				int i = tmPotentialUserMapper.insertCounselorInfo(memberDto);
				logger.info("新增了" + i + "条记录");
			} else {
				logger.info("已有顾问");
				// 更新
				memberDto.setUpdateDate(new Date());
				tmPotentialUserMapper.updateCounselorInfo(memberDto);
			}
			resultMap.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_SUCCESS);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			resultMap.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_ERROR);
		}
		return resultMap;
	}

	/**
	 * 更新验证码
	 * 
	 * @author QianKun
	 * @date 2017年3月8日
	 * @param memberDto
	 */
	public Map<String, Object> updateIdentifyingCode(MemberDto memberDto, String openId) {
		logger.info("开始生产验证码");
		Map<String, Object> resultMap = new HashMap<>();
		Date nowDate = new Date();
		// 检测是否在半小时内调用超过3次
		Integer counter = tmPotentialUserMapper.selectRegistCount(openId);
		Date counterDate = tmPotentialUserMapper.selectRegistCountDate(openId);
		logger.info("计数器" + counter);
		if (counter == null) {
			logger.info("第一次调用该接口");
			// 新增一个计数器
			TmPotentialUser record = new TmPotentialUser();
			record.setRegisterCounter(1);
			record.setRegisterCounterDate(nowDate);
			record.setDeviceOpenId(openId);
			int a = tmPotentialUserMapper.updateRegisterCounter(record);
			logger.info("新增了" + a + "个计数器");
			resultMap = sendRandom(memberDto, openId);
		} else {
			Long diffTime = (nowDate.getTime() - counterDate.getTime()) / 1000;
			if (diffTime <= 1800) {
				logger.info("时间还在30分钟内之内，计数器+1");
				Example example = new Example(TmPotentialUser.class);
				example.createCriteria().andCondition("DEVICE_OPEN_ID=", openId);
				TmPotentialUser record = new TmPotentialUser();
				record.setRegisterCounter(counter + 1);
				int a = tmPotentialUserMapper.updateByExampleSelective(record, example);
				if (a == 1) {
					logger.info("计数器+1");
				}
				if (counter + 1 < 3) {
					logger.info("30分钟内调用次数小于3次，可直接调用");
					resultMap = sendRandom(memberDto, openId);
				} else {
					logger.info("30分钟内调用次数超过3次，需校验随机验证码");
					// 校验输入的验证码和当前验证码是否一致
					String random = tmPotentialUserMapper.selectRandom(openId);
					if (CheckUtil.NullOrEmpty(memberDto.getRandomcode())) {
						String rm = randomCode(openId);
						// resultMap = sendRandom(memberDto, openId);
						logger.info("重新生成的随机验证码为：" + rm);
						resultMap.put("flag", "2");
						resultMap.put("resultMsg", "请输入正确的验证码！");
						resultMap.put("random", rm);
					} else {
						if (memberDto.getRandomcode().equalsIgnoreCase(random)) {
							logger.info("页面输入的随机验证码正确，可以注册");
							resultMap = sendRandom(memberDto, openId);
						} else {
							logger.info("页面输入的随机验证码不正确，重新输入");
							String rm = randomCode(openId);
							logger.info("重新生成的随机验证码为：" + rm);
							resultMap.put("flag", "2");
							resultMap.put("resultMsg", "请输入正确的验证码！");
							resultMap.put("random", rm);
						}
					}
				}
			} else {
				logger.info("已超过30分钟，重新计数！");
				TmPotentialUser record = new TmPotentialUser();
				record.setRegisterCounter(1);
				record.setRegisterCounterDate(nowDate);
				record.setDeviceOpenId(openId);
				int a = tmPotentialUserMapper.updateRegisterCounter(record);
				if (a == 1) {
					logger.info("重置计数器");
				}
				resultMap = sendRandom(memberDto, openId);
			}
		}
		return resultMap;
	}

	public Map<String, Object> sendRandom(MemberDto memberDto, String openId) {
		Map<String, Object> resultMap = new HashMap<>();
		memberDto.setOpenId(openId);
		String Num = "";
		List<MemberDto> members = tmPotentialUserMapper.queryPotential(openId);
		if (members.size() > 0) {
			if (members.get(0).getPhone() != null) {
				if (members.get(0).getPhone().equals(memberDto.getPhone())) {
					List<MemberDto> list = tmPotentialUserMapper.queryIdentifyingCode(openId);
					if (list != null && list.size() > 0) {
						Num = list.get(0).getIdentifyingCode();
					} else {
						// 生成验证码
						for (int i = 0; i < 6; i++) {
							// 代码扫描 1612
							String a = String.valueOf(new SecureRandom().nextInt());
							Num += a.charAt(6);
						}
						memberDto.setIdentifyingCode(Num);
						tmPotentialUserMapper.updateIdentifyingCode(memberDto);
					}
				} else {
					// 生成验证码
					for (int i = 0; i < 6; i++) {
						// 代码扫描 1612
						String a = String.valueOf(new SecureRandom().nextInt());
						Num += a.charAt(6);
					}
					memberDto.setIdentifyingCode(Num);
					tmPotentialUserMapper.updateIdentifyingCode(memberDto);
				}
			} else {
				// 生成验证码
				for (int i = 0; i < 6; i++) {
					// 代码扫描 1612
					String a = String.valueOf(new SecureRandom().nextInt());
					Num += a.charAt(6);
				}
				memberDto.setIdentifyingCode(Num);
				tmPotentialUserMapper.updateIdentifyingCode(memberDto);
			}
		}
		logger.info("发送短信To：" + memberDto.getPhone() + "验证码为：" + Num);
		String s = SmsHttpClient2.sendSms(smsPass, smsKey, SMS_TEMPLATEID_SC, memberDto.getPhone(), Num);
		logger.info("发送短信————End");
		logger.info("返回码————" + s);
		resultMap.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_SUCCESS);
		return resultMap;
	}

	/**
	 * 注册会员(车主)
	 * 
	 * @author QianKun
	 * @date 2017年3月8日
	 * @param memberDto
	 */
	public Map<String, Object> insertCarOwner(@RequestBody CarOwnerDto CarOwnerDto, String openId) {
		Map<String, Object> map = new HashMap<>();
		Date nowDate = new Date();
		// 检测是否在半小时内调用超过3次
		Integer counter = tmPotentialUserMapper.selectRegistCount(openId);
		Date counterDate = tmPotentialUserMapper.selectRegistCountDate(openId);
		logger.info("计数器" + counter);
		if (counter == null) {
			logger.info("第一次调用该接口");
			// 新增一个计数器
			TmPotentialUser record = new TmPotentialUser();
			record.setRegisterCounter(1);
			record.setRegisterCounterDate(nowDate);
			record.setDeviceOpenId(openId);
			int a = tmPotentialUserMapper.updateRegisterCounter(record);
			if (a == 1) {
				logger.info("新增了" + a + "个计数器");
				map = register(CarOwnerDto, openId);
			} else {
				logger.info("openId不存在");
			}
		} else {
			Long diffTime = (nowDate.getTime() - counterDate.getTime()) / 1000;
			if (diffTime <= 1800) {
				logger.info("时间还在30分钟内之内，计数器+1");
				Example example = new Example(TmPotentialUser.class);
				example.createCriteria().andCondition("DEVICE_OPEN_ID=", openId);
				TmPotentialUser record = new TmPotentialUser();
				record.setRegisterCounter(counter + 1);
				int a = tmPotentialUserMapper.updateByExampleSelective(record, example);
				if (a == 1) {
					logger.info("计数器+1");
				}
				if (counter + 1 <= 3) {
					logger.info("30分钟内调用次数小于3次，可直接调用");
					map = register(CarOwnerDto, openId);
				} else {
					logger.info("30分钟内调用次数超过3次，需校验随机验证码");
					// 校验输入的验证码和当前验证码是否一致
					String random = tmPotentialUserMapper.selectRandom(openId);
					if (CarOwnerDto.getRandomcode().equalsIgnoreCase(random)) {
						logger.info("页面输入的随机验证码正确，可以注册");
						map = register(CarOwnerDto, openId);
					} else {
						logger.info("页面输入的随机验证码不正确，重新输入");
						String rm = randomCode(openId);
						logger.info("重新生成的随机验证码为：" + rm);
						map.put("flag", "2");
						map.put("resultMsg", "请输入正确的验证码！");
						map.put("random", rm);
					}
				}
			} else {
				logger.info("已超过30分钟，重新计数！");
				TmPotentialUser record = new TmPotentialUser();
				record.setRegisterCounter(1);
				record.setRegisterCounterDate(nowDate);
				record.setDeviceOpenId(openId);
				int a = tmPotentialUserMapper.updateRegisterCounter(record);
				if (a == 1) {
					logger.info("重置计数器");
				}
				map = register(CarOwnerDto, openId);
			}
		}
		logger.info(map);
		logger.info(map.get("flag"));
		logger.info(map.get("resultMsg"));
		return map;
	}

	public Map<String, Object> register(CarOwnerDto CarOwnerDto, String openId) {
		Map<String, Object> map = new HashMap<>();
		List<MemberDto> dto = tmPotentialUserMapper.queryPotential(openId);
		Integer potentialUserId = dto.get(0).getPotentialUserId();
		Integer sourceType = dto.get(0).getSourceType();
		// 判断姓名是否为空
		if (CarOwnerDto.getUserName() != null && CarOwnerDto.getUserName() != "") {
			// 对比页面输入的验证码
			List<MemberDto> memberDto = tmPotentialUserMapper.queryPotential(openId);
			for (MemberDto memberList : memberDto) {
				if (CarOwnerDto.getIdentifyingCode().equals(memberList.getIdentifyingCode())
						&& CarOwnerDto.getPhone().equals(memberList.getPhone())) {
					// 计算时间差(秒)
					Date nowDate = new Date();
					Long diffTime = (nowDate.getTime() - memberList.getIdentifyingCodeDate().getTime()) / 1000;
					if (diffTime <= 120) {
						try {
							// 先判断该手机号是否已存在
//							Integer uesrId = tmPotentialUserMapper.queryCarOwner(CarOwnerDto.getPhone());
							//查询userId不带sourceType
							Integer uesrId = tmPotentialUserMapper.queryCarOwnerId(CarOwnerDto.getPhone());
							logger.info("uesrId====" + uesrId);
							if (uesrId == null) {
								logger.info("可以注册");
								Long carOwnerId = tmPotentialUserMapper.quertCarOwnerId();
								// 新增一个车主
								CarOwnerDto.setUserId(carOwnerId.toString());
								tmPotentialUserMapper.saveCarOwner(CarOwnerDto);
								// 根据手机号查出该车主的ID
								CarOwnerDto carOwnerRelation = new CarOwnerDto();
								carOwnerRelation.setUserId(carOwnerId.toString());
								carOwnerRelation.setPotentialUserId(potentialUserId.toString());
								tmPotentialUserMapper.saveCarOwnerRelation(carOwnerRelation);
								logger.info("注册会员成功");
								map.put("flag", "1");
								map.put("resultMsg", "注册成功");
								logger.info("注册完成发积分_Start");
								EventCommitQuesionnaireDTO etDto = new EventCommitQuesionnaireDTO();
								etDto.setUserId(carOwnerId.intValue());
								logger.info("USER_ID为：" + carOwnerId.intValue());
								etDto.setPhone(CarOwnerDto.getPhone());
								logger.info("PHONE为：" + CarOwnerDto.getPhone());
								BizEvent event = new BizEvent();
								event.setEventKey("HYZC" + "-" + etDto.getUserId() + "-" + etDto.getPhone());
								event.setEventBizType(EventBizType.REGISTER);
								event.setEventBizStep(EventBizStep.REGISTER_SIGNIN);
								event.setEventData(MapConverUtil.PO2Map(etDto));
								eventService.sendEvent2MQ(event);
								logger.info("注册完成发积分_End");
							} else {
								logger.info("该手机已被注册！");
								// 判断该车主绑定用户于当前用户是否是同一人
//								Long potentialId = tmPotentialUserMapper
//										.queryPotentialUserId(Long.valueOf(uesrId.toString()));
								//查询潜客ID 带上sourceType
								Long SOURCE_TYPE = tmPotentialUserMapper
										.queryPotentialIdByType(Long.valueOf(uesrId.toString()),sourceType);
								if (SOURCE_TYPE.equals(sourceType)) {
									logger.info("是同一用户，无需再次绑定");
									map.put("flag", "0");
									map.put("resultMsg", "您已用该手机注册过，无需再次注册");
								} else {
									logger.info("不是同一个潜客身份，需再次绑定");
									CarOwnerDto carOwnerRelation = new CarOwnerDto();
									carOwnerRelation.setUserId(uesrId.toString());
									carOwnerRelation.setPotentialUserId(potentialUserId.toString());
									tmPotentialUserMapper.saveCarOwnerRelation(carOwnerRelation);
									map.put("flag", "1");
									map.put("resultMsg", "注册成功");
								}
							}
						} catch (Exception e) {
							logger.info("Exception:", e);
							// map.put("errorCode", "1");
							// map.put("errorMsg", e.getMessage());
						}
					} else {
						logger.info("验证码超时！");
						map.put("flag", "0");
						map.put("resultMsg", "验证码超时！");
					}
				} else {
					logger.info("手机号或验证码错误！");
					map.put("flag", "0");
					map.put("resultMsg", "手机号或验证码错误！");
				}
			}
		} else {
			map.put("flag", "0");
			map.put("resultMsg", "姓名不能为空！");
		}
		return map;
	}

	/**
	 * 销售/售后顾问查询
	 * 
	 * @author WangHuicheng
	 * @date 2016年12月14日
	 * @param positionId
	 * @param dealerCode
	 * @return
	 */
	public List<CounselorDto> getCounselorData(String dealerCode, String positionId) {
		List<CounselorDto> dtoList = tmPotentialUserMapper.queryCounselorData(dealerCode, positionId);
		return dtoList;
	}

	/**
	 * 车主认证(绑车) resultCode:
	 * "-1":拿不到车辆信息;"0":没有该车;"1":有车没有绑定关系;"2":是本人绑定;"3":该车已被绑定，不是本人
	 * 
	 * @author QianKun
	 * @date 2017年3月9日
	 * @param carInfoDto
	 * @return
	 */
	public Map<String, Object> saveCarInfo(@RequestBody CarInfoDto carInfoDto, String openId) {
		Map<String, Object> map = new HashMap<String, Object>();
		Date nowDate = new Date();
		// 检测是否在半小时内调用超过3次
		Integer counter = tmPotentialUserMapper.selectBindingCount(openId);
		Date counterDate = tmPotentialUserMapper.selectBindingCountDate(openId);
		logger.info("计数器" + counter);
		if (counter == null) {
			logger.info("第一次调用该接口");
			// 新增一个计数器
			TmPotentialUser record = new TmPotentialUser();
			record.setBindingCounter(1);
			record.setBindingCounterDate(nowDate);
			record.setDeviceOpenId(openId);
			int a = tmPotentialUserMapper.updateBindingCounter(record);
			if (a == 1) {
				logger.info("新增了" + a + "个计数器");
				map = bindingCar(carInfoDto, openId);
			} else {
				logger.info("该OPENID不存在");
			}
		} else {
			Long diffTime = (nowDate.getTime() - counterDate.getTime()) / 1000;
			if (diffTime <= 1800) {
				logger.info("时间还在30分钟内之内，计数器+1");
				Example example = new Example(TmPotentialUser.class);
				example.createCriteria().andCondition("DEVICE_OPEN_ID=", openId);
				TmPotentialUser record = new TmPotentialUser();
				record.setBindingCounter(counter + 1);
				int a = tmPotentialUserMapper.updateByExampleSelective(record, example);
				if (a == 1) {
					logger.info("计数器+1");
				}
				if (counter + 1 <= 3) {
					logger.info("30分钟内调用次数小于3次，可直接调用");
					map = bindingCar(carInfoDto, openId);
				} else {
					logger.info("30分钟内调用次数超过3次，需校验随机验证码");
					// 校验输入的验证码和当前验证码是否一致
					String random = tmPotentialUserMapper.selectRandom(openId);
					// logger.info("查询到的随机数为：" + random);
					// logger.info("前台传入的随机数为：" + carInfoDto.getRandomcode());
					if (!CheckUtil.NullOrEmpty(random)) {
						if (carInfoDto.getRandomcode().equalsIgnoreCase(random)) {
							logger.info("页面输入的随机验证码正确，可以注册");
							map = bindingCar(carInfoDto, openId);
						} else {
							logger.info("页面输入的随机验证码不正确，重新输入");
							String rm = randomCode(openId);
							logger.info("重新生成的随机验证码为：" + rm);
							map.put("flag", "2");
							map.put("resultMsg", "请输入正确的验证码！");
							map.put("random", rm);
						}
					} else {
						logger.info("页面输入的随机验证码不正确，重新输入");
						String rm = randomCode(openId);
						logger.info("重新生成的随机验证码为：" + rm);
						map.put("flag", "2");
						map.put("resultMsg", "请输入正确的验证码！");
						map.put("random", rm);
					}
				}
			} else {
				logger.info("已超过30分钟，重新计数！");
				TmPotentialUser record = new TmPotentialUser();
				record.setBindingCounter(1);
				record.setBindingCounterDate(nowDate);
				record.setDeviceOpenId(openId);
				int a = tmPotentialUserMapper.updateBindingCounter(record);
				if (a == 1) {
					logger.info("重置计数器");
				}
				map = bindingCar(carInfoDto, openId);
			}
		}
		return map;
	}

	/**
	 * @param carinfodto
	 * @return
	 */
	public Map<String, Object> updateCarinfo(CarInfoDto carinfodto) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("errorCode", "0");
		try {
			Example ex = new Example(TmCarInfo.class);
			Criteria criteria = ex.createCriteria();
			if (!CheckUtil.NullOrEmpty(carinfodto.getVin())) {
				criteria.andCondition("VIN =", carinfodto.getVin());
			}
			if (!CheckUtil.NullOrEmpty(carinfodto.getCarId())) {
				criteria.andCondition("CAR_ID =", carinfodto.getCarId());
			}

			TmCarInfo car = new TmCarInfo();
			car.setInsurer(carinfodto.getInsurer());
			car.setLicenseNo(carinfodto.getLicenseNo());
			car.setBillDate(carinfodto.getBillDate());
			car.setInsuranceStartDate(carinfodto.getInsuranceStartDate());
			car.setVehicleDate(carinfodto.getVehicleDate());
			car.setUpdateDate(new Date());
			tmCarInfoMapper.updateByExampleSelective(car, ex);
		} catch (Exception e) {
			logger.info("Exception:", e);
			map.put("errorCode", "1");
			map.put("errorMsg", e.getMessage());
		}
		return map;

	}

	/**
	 * 获取保险公司
	 * 
	 * @author Administrator
	 * @date 2017年4月13日
	 * @return
	 */
	public List<InsuranceDto> getInsuranceMap() {
		return tmPotentialUserMapper.getInsurance();
	}

	/**
	 * 修改用户车子绑定状态
	 * 
	 * @param ownercarrelationdto
	 * @return
	 */
	public Map<String, Object> updateCarinfoStu(String carId, String userId) {
		logger.info("userId：" + userId + "   carId:" + carId);
		Map<String, Object> map = new HashMap<>();
		if (CheckUtil.NullOrEmpty(carId)) {
			map.put("errorCode", "1");
			map.put("errorMsg", "车辆ID不能为空");
			return map;
		}
		if (CheckUtil.NullOrEmpty(userId)) {
			map.put("errorCode", "1");
			map.put("errorMsg", "用户ID不能为空");
			return map;
		}
		TmOwnerCarRelation ocr = new TmOwnerCarRelation();
		ocr.setCarId(Integer.valueOf(carId));
		ocr.setUserId(Integer.valueOf(userId));
		ocr.setStatus((short) 0);
		TmOwnerCarRelation car = tmOwnerCarRelationMapper.selectOne(ocr);
		if (car == null) {
			map.put("errorCode", "1");
			map.put("errorMsg", "无法查询到该用户的车辆信息");
		} else {
			TmOwnerCarRelation ocr1 = new TmOwnerCarRelation();
			ocr1.setId(car.getId());
			ocr1.setStatus((short) 1);
			tmOwnerCarRelationMapper.updateByPrimaryKeySelective(ocr1);
			tmCarInfoMapper.deleteByPrimaryKey(Integer.valueOf(carId));
			map.put("errorCode", "0");
			map.put("errorMsg", "删除车辆成功");
		}
		return map;

	}

	public Map<String, Object> bindingCar(CarInfoDto carInfoDto, String userId) {
		Map<String, Object> result = new HashMap<>();
		String vin = carInfoDto.getVin();
		String engine = carInfoDto.getEngine();
		vin = "LJ1********" + vin;
		Integer carCou = tmPotentialUserMapper.checkCarBindExist(vin, engine);
		if (carCou > 0) {
			result.put("flag", "0");
			result.put("resultMsg", "车辆已被绑定！");
			return result;
		}
		TmCarInfo record = new TmCarInfo();
		record.setVin(vin);
		record.setEngine(engine);
		TmCarInfo reCar = tmCarInfoMapper.selectOne(record);
		Integer carId = 0;
		if (reCar == null) {
			record.setModelCodeNew("V754WLVXLL1C-H642Y");
			record.setVehicleDate(new Date());
			tmCarInfoMapper.insertSelective(record);
		} else {
			carId = reCar.getCarId();
		}

		TmCarInfo car = new TmCarInfo();
		car.setVin(vin);
		car.setEngine(engine);
		TmCarInfo carInfo = tmCarInfoMapper.selectOne(car);
		if (carInfo != null) {
			carId = carInfo.getCarId();
			// 绑定车主-车辆关系
			TmOwnerCarRelation ocr = new TmOwnerCarRelation();
			ocr.setUserId(Integer.valueOf(userId));
			ocr.setCarId(carId);
			ocr.setStatus((short) 0);
			ocr.setCreateDate(new Date());
			int s = tmOwnerCarRelationMapper.insertSelective(ocr);
			if (s == 1) {
				result.put("flag", "1");
				result.put("resultMsg", "绑定成功！");
				result.put("vin", vin);
				// logger.info("绑车事件");
				// EventRegisterBindCarDTO rgbOrderDto = new
				// EventRegisterBindCarDTO();
				// rgbOrderDto.setVin(carInfoDto.getVin());
				// rgbOrderDto.setPhone(carInfoDto.getPhone());
				// rgbOrderDto.setUserId(Integer.valueOf(carInfoDto.getUserId()));
				// BizEvent event = new BizEvent();
				// event.setEventBizType(EventBizType.REGISTER);
				// event.setEventBizStep(EventBizStep.REGISTER_BIND);
				// event.setEventKey(rgbOrderDto.getVin() + openId);
				// event.setEventData(MapConverUtil.PO2Map(rgbOrderDto));
				// String z = eventService.sendEvent2MQ(event);
				// logger.info("MQ返回结果>>>>>>>>>>>>>>>>>>>>" + z);
				//
				// // 发放卡券
				// logger.info("自动发放卡券");
				// SendTicket ticketDto = new SendTicket();
				// ticketDto.setBizCode(Integer.valueOf(EventBizType.REPAIR_APPOINTMENT.toString()));
				// ticketDto.setTriggerCode(Integer.valueOf(EventBizStep.REPAIR_APPOINTMENT_SEND.toString()));
				// ticketDto.setUserId(potentialUserId);
				// ticketDto.setDealerCode("");
				// ticketDto.setBatchId("");
				// BizEvent et = new BizEvent();
				// et.setEventBizType(EventBizType.SEND_TICKET);
				// et.setEventBizStep(EventBizStep.SEND_TICKTE_TO_USER);
				// et.setEventKey("TICKET:" + ticketDto.getUserId() + ":" + new
				// Date());
				// et.setEventData(MapConverUtil.PO2Map(ticketDto));
				// String x = eventService.sendEvent2MQ(et);
				// logger.info("发放卡券MQ返回结果>>>>>>>>>>>>>>>>>>>>" + x);
			}
		} else {
			result.put("flag", "0");
			result.put("resultMsg", "绑定失败！");
		}

		return result;
	}

	public void sendTicketToMq(Integer userId, Integer carId,String coDeaCode) throws Exception {
		logger.info("判断该人是否首次绑车");
		TmOwnerCarRelation ocr = new TmOwnerCarRelation();
		ocr.setUserId(userId);
		ocr.setCarId(carId);
		Integer a = tmOwnerCarRelationMapper.selectCount(ocr);
		if (a == 0) {
			logger.info("首次绑车，发放卡券");
			// 发放卡券
			logger.info("自动发放卡券");
			SendTicket ticketDto = new SendTicket();
			ticketDto.setBizCode(1001);
			ticketDto.setTriggerCode(10011002);
			ticketDto.setUserId(userId);
			logger.info("该用户的销售店为：" + coDeaCode);
			if (CheckUtil.NullOrEmpty(coDeaCode)) {
				ticketDto.setDealerCode(coDeaCode);
			} else {
				ticketDto.setDealerCode("");
			}
			ticketDto.setBatchId("");
			ticketDto.setBizId(carId.toString());
			BizEvent et = new BizEvent();
			et.setEventBizType(EventBizType.SEND_TICKET);
			et.setEventBizStep(EventBizStep.SEND_TICKTE_TO_USER);
			et.setEventKey("TICKET:" + ticketDto.getUserId() + ":" + new Date());
			et.setEventData(MapConverUtil.PO2Map(ticketDto));
			String x = eventService.sendEvent2MQ(et);
			logger.info("发放卡券MQ返回结果>>>>>>>>>>>>>>>>>>>>" + x);
		} else {
			logger.info("不是首次绑车，不发放卡券");
		}
	}

	/**
	 * 绑定车辆后发送VIN至MQ（维修履历同步）
	 * 
	 * @author Qiankun
	 * @date 2017年3月24日
	 * @param vin
	 * @throws Exception
	 */
	public void maintenanceMQ(TmCarInfo carInfoDto, String userId) throws Exception {
		logger.info("Start:");
		EventMaintenanceOrderDTO mtOrderDto = new EventMaintenanceOrderDTO();
		mtOrderDto.setVin(carInfoDto.getVin());
		Map<String, Object> map = new HashMap<>();
		map.put("vin", mtOrderDto.getVin());
		BizEvent event = new BizEvent();
		event.setEventBizType(EventBizType.REGISTER);
		event.setEventBizStep(EventBizStep.REGISTER_RECORD_SYNC);
		event.setEventKey(mtOrderDto.getVin() + carInfoDto.getLinkMan() + userId);
		// logger.info(mtOrderDto.getVin());
		event.setEventData(MapConverUtil.PO2Map(mtOrderDto));
		String s = eventService.sendEvent2MQ(event);
		logger.info("MQ返回结果>>>>>>>>>>>>>>>>>>>>" + s);
	}

	/**
	 * 微信关注
	 * 
	 * @author QianKun
	 * @date 2017年3月25日
	 * @param event
	 * @return
	 */
	public MQReceiveResult receiveEvent(@RequestBody BizEvent event) {
		// logger.info(event.getEventData());
		if (event.getEventBizStep().equals(EventBizStep.WECHAT_USER_ATTENTION)) {
			// 微信关注
			logger.info("关注事件");
			try {
				EventWechatAttentionDTO customerInfo = new EventWechatAttentionDTO();
				customerInfo.setDeviceOpenId(event.getEventData().get("DEVICEOPENID").toString());
				customerInfo.setSourceType((Integer) event.getEventData().get("SOURCETYPE"));
				customerInfo.setAppType((Integer) event.getEventData().get("APPTYPE"));
				long CDate = (long) event.getEventData().get("CREATEDATE");
				long SDate = (long) event.getEventData().get("SUBSCRIBEDATE");
				Date CreateDate = new Date(CDate);
				Date SubscribeDate = new Date(SDate);
				customerInfo.setCreateDate(CreateDate);
				customerInfo.setSubscribeDate(SubscribeDate);
				customerInfo.setStatus((Integer) event.getEventData().get("STATUS"));
				logger.info("-----------------------");
				customerInfo.setNickName(event.getEventData().get("NICKNAME").toString());
				customerInfo.setSex(event.getEventData().get("SEX").toString());
				customerInfo.setCity(event.getEventData().get("CITY").toString());
				customerInfo.setProvince(event.getEventData().get("PROVINCE").toString());
				customerInfo.setCountry(event.getEventData().get("COUNTRY").toString());
				customerInfo.setHeadImgurl(event.getEventData().get("HEADIMGURL").toString());

				// 判断该用户信息是否已存在
				List<MemberDto> PotentialDto = tmPotentialUserMapper.queryPotential(customerInfo.getDeviceOpenId());

				if (CheckUtil.NullOrEmpty(PotentialDto)) {
					// 该用户信息不存在
					TmPotentialUser user = new TmPotentialUser();
					user.setSourceType(customerInfo.getSourceType());
					user.setAppType(customerInfo.getAppType());
					user.setCreateDate(customerInfo.getCreateDate());
					user.setStatus(customerInfo.getStatus());
					user.setSubscribeDate(customerInfo.getSubscribeDate());
					user.setDeviceOpenId(customerInfo.getDeviceOpenId());
					user.setNickname(customerInfo.getNickName());
					user.setSex(customerInfo.getSex());
					user.setCity(customerInfo.getCity());
					user.setProvince(customerInfo.getProvince());
					user.setCountry(customerInfo.getCountry());
					user.setHeadImgurl(customerInfo.getHeadImgurl());
					user.setDealerCode(customerInfo.getDealerCode());
					logger.info("Start：" + user.getDealerCode());
					// 插入一条新关注用户信息
					tmPotentialUserMapper.insertSelective(user);
					logger.info("End");
					MQReceiveResult result = new MQReceiveResult();
					result.setMessage("");
					result.setResult("200");
					// 发放卡券
					logger.info("查询该用户潜客ID");
					// Integer potentialUserId =
					// tmPotentialUserMapper.queryPotentialId(customerInfo.getDeviceOpenId());
					// logger.info("潜客ID为：" + potentialUserId);
					// logger.info("自动发放卡券");
					// SendTicket ticketDto = new SendTicket();
					// ticketDto.setBizCode(1006);
					// ticketDto.setTriggerCode(10061001);
					// ticketDto.setUserId(potentialUserId);
					// ticketDto.setDealerCode("");
					// ticketDto.setBatchId("");
					// ticketDto.setBizId(user.getDeviceOpenId());
					// BizEvent et = new BizEvent();
					// et.setEventBizType(EventBizType.SEND_TICKET);
					// et.setEventBizStep(EventBizStep.SEND_TICKTE_TO_USER);
					// et.setEventKey("TICKET:" + ticketDto.getUserId() + ":" +
					// new Date().getTime());
					// et.setEventData(MapConverUtil.PO2Map(ticketDto));
					// String s = eventService.sendEvent2MQ(et);
					// logger.info("发放卡券MQ返回结果>>>>>>>>>>>>>>>>>>>>" + s);
					return result;
				} else {
					logger.info("用户信息已存在");
					// 更新用户关注状态
					MemberDto statusDto = new MemberDto();
					statusDto.setOpenId(customerInfo.getDeviceOpenId());
					statusDto.setStatus(customerInfo.getStatus());
					tmPotentialUserMapper.updateStatus(statusDto);
					MQReceiveResult result = new MQReceiveResult();
					result.setMessage("");
					result.setResult("200");
					return result;
				}
			} catch (Exception e) {
				logger.error("插入error", e);
				MQReceiveResult result = new MQReceiveResult();
				result.setMessage("");
				result.setResult("500");
				return result;
			}
		} else if (event.getEventBizStep().equals(EventBizStep.WECHAT_USER_UNATTENTION)) {
			// 取消关注
			logger.info("取消关注");
			try {
				EventWechatAttentionDTO customer = new EventWechatAttentionDTO();
				customer.setDeviceOpenId(event.getEventData().get("DEVICEOPENID").toString());
				logger.info("取消关注的OPENID为:" + customer.getDeviceOpenId());
				// 更新用户关注状态
				MemberDto statusDto = new MemberDto();
				statusDto.setOpenId(customer.getDeviceOpenId());
				statusDto.setStatus(10011002);
				tmPotentialUserMapper.updateStatus(statusDto);
				logger.info("状态更新完成");
				MQReceiveResult result = new MQReceiveResult();
				result.setMessage("");
				result.setResult("200");
				try {
					// 清除自动绑车相关数据
					tmPotentialUserMapper.clearQrCodeData(customer.getDeviceOpenId());
				} catch (Exception e) {
					logger.info("清除二维码临时数据错误.=======================");
				}
				return result;
			} catch (Exception e) {
				logger.error("更新error", e);
				MQReceiveResult result = new MQReceiveResult();
				result.setMessage("");
				result.setResult("500");
				return result;
			}
		} else {
			//
			MQReceiveResult result = new MQReceiveResult();
			result.setMessage("");
			result.setResult("200");
			return result;
		}
	}

	/**
	 * @author QianKun
	 * @date 2017年3月27日
	 * @param dealerCode
	 * @param userId
	 */
	public void updateDealerCode(String dealerCode, String userId) {
		TmCarOwner c = new TmCarOwner();
		c.setUserId(Integer.valueOf(userId));
		c.setDealerCode(dealerCode);
		tmCarOwnerMapper.updateByPrimaryKeySelective(c);
	}

	/**
	 * 修改手机号(车主)
	 * 
	 * @date 2017年4月7日
	 * @param memberDto
	 */
	public Map<String, Object> updatePhone(CarOwnerDto CarOwnerDto, String openId) {
		Map<String, Object> map = new HashMap<>();
		// 先判断该手机号是否已存在
		Integer uesrId = tmPotentialUserMapper.queryCarOwner(CarOwnerDto.getPhone());
		if (uesrId == null) {
			// 对比页面输入的验证码
			List<MemberDto> memberDto = tmPotentialUserMapper.queryMember(openId);
			for (MemberDto memberList : memberDto) {
				if (CarOwnerDto.getIdentifyingCode().equals(memberList.getIdentifyingCode())) {
					logger.info(memberList.getIdentifyingCode());
					logger.info("PotentialUserId" + memberList.getPotentialUserId());
					Date nowDate = new Date();
					// 计算时间差(秒)
					Long diffTime = (nowDate.getTime() - memberList.getIdentifyingCodeDate().getTime()) / 1000;
					if (diffTime <= 300) {
						TmCarOwner c = new TmCarOwner();
						c.setUserId(memberList.getUserId());
						c.setPhone(CarOwnerDto.getPhone());
						tmCarOwnerMapper.insertSelective(c);
					} else {
						//
						map.put("resultMsg", "验证码超时！");
					}
				} else {
					//
					map.put("resultMsg", "验证码错误！");
				}
			}
		} else {
			map.put("resultMsg", "该手机已被注册！");
		}
		return map;
	}

	/**
	 * 个人资料查询
	 * 
	 * @author Administrator
	 * @date 2017年4月28日
	 * @param openId
	 * @return
	 */
	public List<MemberDto> getCustomerInfo(String openId) {
		List<MemberDto> dtoList = tmPotentialUserMapper.queryCustomerInfo(openId);
		return dtoList;
	}

	/**
	 * 企业会员注册
	 * 
	 * @param CarOwnerDto
	 * @param openId
	 * @return
	 */
	public Map<String, Object> insertThirdCarOwner(String openId, String phone) {

		Map<String, Object> map = new HashMap<>();
		// 判断该openId是否已存在
		List<MemberDto> thirdMemberDto = tmPotentialUserMapper.queryThirdPotential(openId);
		if (thirdMemberDto == null || thirdMemberDto.size() == 0) {
			logger.info("该openId不存在，进行插入：");
			// 新增潜客表数据
			TmPotentialUser user = new TmPotentialUser();
			Date newDate = new Date();
			user.setDeviceOpenId(openId);
			user.setSubscribeDate(newDate);
			user.setSourceType(10011002);
			user.setCreateDate(newDate);
			logger.info("插入潜客表");
			tmPotentialUserMapper.insertSelective(user);
			// 新增一个车主
			logger.info("插入车主表");
			Long carOwnerId = tmPotentialUserMapper.quertCarOwnerId();
			logger.info("插入车主carOwnerId：" + carOwnerId + "电话：" + phone);
			
			tmPotentialUserMapper.saveThirdCarOwner(carOwnerId, phone);
			logger.info("通过phone拿到车主信息");
			List<MemberDto> memberDto = tmPotentialUserMapper.queryThirdPotential(openId);
			logger.info("通过openId拿到潜客信息");
			if (memberDto != null && memberDto.size() != 0) {
				// 查询potentialUserId
				String potentialUserId = String.valueOf(memberDto.get(0).getPotentialUserId());
				// 将车主和潜客绑定
				CarOwnerDto carOwnerRelation = new CarOwnerDto();
				carOwnerRelation.setUserId(carOwnerId.toString());
				carOwnerRelation.setPotentialUserId(potentialUserId);
				logger.info(
						"拿到potentialUserId插入中间表，potentialUserId：" + potentialUserId + "车主ID，carOwnerId：" + carOwnerId);
				tmPotentialUserMapper.saveCarOwnerRelation(carOwnerRelation);
				map.put("resultMsg", "注册成功!");

			} else {
				map.put("resultMsg", "注册失败！");
			}
		} else {
			String carOwnerPhone = thirdMemberDto.get(0).getPhone();
			Long carUserId = Long.valueOf(thirdMemberDto.get(0).getUserId());
			// logger.info("获得已存在openId的手机号码：" + carOwnerPhone + "已存在的userId：" +
			// carUserId);
			if (phone == carOwnerPhone) {
				logger.info("电话没有改变，不做任何操作。企业注册成功");
				map.put("resultMsg", "注册成功!");
			} else {
				logger.info("电话改变，跟新手机号码。企业注册成功");
				tmPotentialUserMapper.updateCarOwnerPhone(carUserId, phone);
				map.put("resultMsg", "注册成功!");
			}
		}
		return map;
	}

	/**
	 * 车主认证匹配销售店
	 * 
	 * @author Administrator
	 * @date 2017年6月1日
	 * @param latitude
	 * @param longitude
	 * @param openId
	 * @return
	 */
	public TmDealer selectDealer(String regionName, String latitude, String longitude, String openId) {
		TmDealer result = new TmDealer();
		// 根据openId查车主车辆VIN
		List<CarInfoDto> carList = tmDealerMapper.carInfo(openId);
		String vin = carList.get(0).getVin();
		// logger.info("车辆VIN>>>>>>>>>" + vin);
		// 1.绑定车辆的最后一次保养店，且最后一次保养店非S开头/非JGD001/ JGD002的售后保养店
		List<TmDealer> firstList = tmDealerMapper.firstDealer(vin);
		if (firstList.size() == 0) {
			List<TmDealer> firstLists = tmDealerMapper.firstDealers(vin);
			if (firstLists.size() == 0) {
				logger.info("没有符合第一条的销售店");
				// 绑定车辆购车店，且非16开头/非JGD001/ 非JGD002（非直销车）
				List<TmDealer> secondList = tmDealerMapper.secondDealer(vin);
				if (secondList.size() == 0) {
					logger.info("没有符合第二条的销售店");
					// 距离注册人定位最近的销售店
					List<TmDealer> thirdList = tmDealerMapper.thirdDealer(regionName, longitude, latitude);
					result = thirdList.get(0);
					// logger.info("符合第三条件的销售店>>>>>>>" +
					// result.getDealerCode());
				} else {
					result = secondList.get(0);
					logger.info("符合第二条件的销售店>>>>>>>" + result.getDealerCode());
				}
			} else {
				result = firstLists.get(0);
				logger.info("符合第一条件的销售店>>>>>>>" + result.getDealerCode());
			}
		} else {
			result = firstList.get(0);
			logger.info("符合第一条件的销售店>>>>>>>" + result.getDealerCode());
		}
		return result;
	}

	/**
	 * 推送消息给某个用户
	 * 
	 * @author Administrator
	 * @date 2017年6月1日
	 * @return
	 */
	public void sendMessage(String openId, String content) {
		logger.info("该用户的openId为>>>>>>>>" + openId);
		String url = "";
		String message = "";
		// 获取TOKEN
		String s = customerServiceInterface.genToken();
		logger.info("获取的返回值为>>>>>>>>>>" + s);
		JSONObject json = JSONObject.fromObject(s);
		if (json == null || json.isNullObject()) {
			logger.info("返回结果为空");
		} else {
			String token = json.getString("token");
			logger.info("返回的token是" + token);
			url = "https://api.weixin.qq.com/cgi-bin/message/mass/preview?access_token=" + token;
			logger.info("POST的URL为>>>>>>>>>" + url);
			message = "{\"touser\":\"" + openId + "\",\"text\":{\"content\":\"" + content + "\"},\"msgtype\":\"text\"}";
			String str = FrameHttpUtil.post(url, message);
			logger.info("接口返回结果>>>>>>>" + str);
		}
	}

	public void mass(String openId_List, String content) {
		String url = "";
		String message = "";
		// 获取TOKEN
		String s = customerServiceInterface.genToken();
		logger.info("获取的返回值为>>>>>>>>>>" + s);
		JSONObject json = JSONObject.fromObject(s);
		if (json == null || json.isNullObject()) {
			logger.info("返回结果为空");
		} else {
			// 拿到TOKEN
			String token = json.getString("token");
			logger.info("返回的token是" + token);
			// 拼接URL
			url = "https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token=" + token;
			logger.info("POST的URL为>>>>>>>>>" + url);
			// 拼接消息体
			message = "{\"touser\":[" + openId_List + "],\"msgtype\": \"text\",\"text\":{\"content\":\"" + content
					+ "\"}}";
			logger.info("内容是>>>>>>>" + message);
			String str = FrameHttpUtil.post(url, message);
			logger.info("接口返回结果>>>>>>>" + str);
		}
	}

	public String randomCode(String openId) {
		String result = CommonUtils.randomCodeZ(4);
		logger.info("生成的验证码为:" + result);
		// 将随机验证码保存到该用户的潜客信息中
		Example ex = new Example(TmPotentialUser.class);
		ex.createCriteria().andCondition("DEVICE_OPEN_ID=", openId);
		TmPotentialUser record = new TmPotentialUser();
		record.setRandomcode(result);
		record.setRandomcodeCreateDate(new Date());
		int i = tmPotentialUserMapper.updateByExampleSelective(record, ex);
		logger.info("更新了" + i + "条");
		return result;
	}

	/**
	 * 投诉信息
	 * 
	 * @date 2017年7月4日
	 * @return
	 * @throws Exception
	 */
	public Map<String, Object> addComplaint(String openId, TtComplaint ttComplaint) throws Exception {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			TtComplaint record = new TtComplaint();
			int potentialId = tmPotentialUserMapper.queryPotentialId(openId);
			logger.info("投诉人的潜客ID为：" + potentialId);
			String oddNumber = tmPotentialUserMapper.selectComplaintNumber(potentialId);
			record.setComplaintContent(ttComplaint.getComplaintContent());
			record.setComplaintType(ttComplaint.getComplaintType());
			record.setDealerCode(ttComplaint.getDealerCode());
			record.setOddNumber(oddNumber);
			record.setUserId(potentialId);
			record.setComplaintDate(new Date());
			record.setState(0);
			ttComplaintMapper.insertSelective(record);
			logger.info("查询投诉人信息");
			Map<String, Object> result = new HashMap<String, Object>();
			result = tmPotentialUserMapper.selectInformation(openId);
			String complainNo = "";
			String mobile = "";
			String name = "";
			if (result.isEmpty()) {
				logger.info("查询不到此人的信息");
			} else {
				complainNo = oddNumber;
				mobile = result.get("MOBILE").toString();
				name = result.get("NAME").toString();
				logger.info("将投诉消息推送到DCMS——START");
				IfMessage<List<EventComplaintDto>> l = new IfMessage<>();
				List<EventComplaintDto> list = new ArrayList<>();
				EventComplaintDto dto = new EventComplaintDto();
				dto.setComplainNo(complainNo);
				dto.setMobile(mobile);
				dto.setName(name);
				dto.setReason(ttComplaint.getComplaintContent());
				list.add(dto);
				l.setIfData(list);
				String time = String.valueOf(new Date().getTime());
				String transferNo = MD5Util.MD5("IC015" + time + CommonConstant.HTTP_CLUB_KEY);
				l.setIfCode("IC001");
				l.setOccurtime(time);
				l.setTransferNo(transferNo);
				l.setDataCnt(1);
				String data = JSON.toJSONString(l).toString();
				logger.info("SendToMQ,data=" + data);
				String s = eventService.sendMessage2MQ(MQChannelType.appSendComplaint, data);
				logger.info("MQ返回结果>>>>>>>>>>>>>>>>>>>>" + s);
				logger.info("将投诉消息推送到DCMS——END");
			}
			resultMap.put("errorCode", "0");
			resultMap.put("errorMsg", "提交成功！");
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			resultMap.put("errorCode", "1");
			resultMap.put("errorMsg", "提交失败！");
		}
		return resultMap;
	}

	/**
	 * 投诉类型
	 * 
	 * @return
	 */
	public List<Map<String, Object>> queryComplaintType() {
		List<Map<String, Object>> result = ttComplaintMapper.queryComplaintType();
		return result;
	}

	/**
	 * 首选店
	 * 
	 * @param openId
	 * @return
	 */
	public Map<String, Object> queryFirstDealer(String openId) {
		Map<String, Object> result = ttComplaintMapper.queryFirstDealer(openId);
		return result;
	}

	/**
	 * 查询未工单评价个数
	 * 
	 * @param openId
	 * @return
	 */
	public Integer queryEvaluationNum(String openId) {
		Integer result = tmPotentialUserMapper.queryEvaluationNum(openId);
		return result;
	}

	public Map<String, Object> sendPointsMessage(PointsChangePO pointsChangePO) {
		try {
			Map<String, Object> result = new HashMap<String, Object>();

			Long potentialUserId = tmPotentialUserMapper.queryPotentialUserId(pointsChangePO.getUserId());
			logger.info("推送积分变更事件到MQ开始");
			// 具体业务参数
			EventPointsChangedDTO eventDate = new EventPointsChangedDTO();
			eventDate.setAfterPoints(pointsChangePO.getAfterPoints());
			eventDate.setBeforePoints(pointsChangePO.getBeforePoints());
			eventDate.setChangePoints(pointsChangePO.getChangePoints());
			eventDate.setReason(pointsChangePO.getReason());
			eventDate.setUserId(Integer.valueOf(pointsChangePO.getUserId().toString()));
			// 业务事件
			BizEvent bizEvent = new BizEvent();
			bizEvent.setEventKey("MANUAL-CHANGE-" + eventDate.getUserId() + ":" + new Date().getTime());
			bizEvent.setEventBizType(EventConstant.EventBizType.COMMON);
			bizEvent.setEventBizStep(EventConstant.EventBizStep.COMMON_POINTS_CHANGED);
			bizEvent.setEventData(MapConverUtil.PO2Map(eventDate));
			// logger.info(bizEvent.toString());
			String returnString = eventService.sendEvent2MQ(bizEvent);

			logger.info("推送积分变更事件到MQ结束:" + returnString);

			logger.info("发送消息通知开始");
			MessageDto dto = new MessageDto();
			if (eventDate.getChangePoints() > 0) {
				// dto.setMessageContent("您的积分因为"+eventDate.getReason()+"+"+eventDate.getChangePoints()+",现有积分为："+eventDate.getAfterPoints()+"，请及时关注！");
				dto.setMessageContent("您的积分因为手工调整，备注原因：" + eventDate.getReason() + "+" + eventDate.getChangePoints()
						+ "分，当前积分：" + eventDate.getAfterPoints() + "分，详情请至个人中心-我的积分查看。");
			} else {
				// dto.setMessageContent("您的积分因为"+eventDate.getReason()+eventDate.getChangePoints()+",现有积分为："+eventDate.getAfterPoints()+"，请及时关注！");
				dto.setMessageContent("您的积分因为手工调整，备注原因：" + eventDate.getReason() + eventDate.getChangePoints()
						+ "分，当前积分：" + eventDate.getAfterPoints() + "分，详情请至个人中心-我的积分查看。");
			}
			dto.setMessageTitle("积分变动");
			dto.setMessageType("40011005");
			dto.setUserId(potentialUserId);
			BizEvent et = new BizEvent();
			et.setEventBizType(EventBizType.SEND_MESSAGE);
			et.setEventBizStep(EventBizStep.SEND_MESSAGE_NOTICE);
			et.setEventKey("MANUAL-CHANGE-MESSAGE-" + dto.getUserId() + ":" + new Date().getTime());
			et.setEventData(MapConverUtil.PO2Map(dto));
			String s = eventService.sendEvent2MQ(et);
			logger.info("发送消息通知结束，MQ返回结果>>>>>>>>>>>>>>>>>>>>" + s);
			result.put("flag", 1);
			result.put("msg", "消息推送成功");
			return result;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
	}

	public Map<String, Object> sendBatchPoints(List<PointsChangePO> pointsChangeList) {
		try {
			Map<String, Object> result = new HashMap<String, Object>();
			if (pointsChangeList != null) {
				for (PointsChangePO pointsChangePO : pointsChangeList) {
					Long potentialUserId = tmPotentialUserMapper.queryPotentialUserId(pointsChangePO.getUserId());
					logger.info("批量推送积分变更事件到MQ开始");
					// 具体业务参数
					EventPointsChangedDTO eventDate = new EventPointsChangedDTO();
					eventDate.setAfterPoints(pointsChangePO.getAfterPoints());
					eventDate.setBeforePoints(pointsChangePO.getBeforePoints());
					eventDate.setChangePoints(pointsChangePO.getChangePoints());
					eventDate.setReason(pointsChangePO.getReason());
					eventDate.setUserId(Integer.valueOf(pointsChangePO.getUserId().toString()));
					// 业务事件
					BizEvent bizEvent = new BizEvent();
					bizEvent.setEventKey("BATCH-CHANGE-" + eventDate.getUserId() + ":" + new Date().getTime());
					bizEvent.setEventBizType(EventConstant.EventBizType.COMMON);
					bizEvent.setEventBizStep(EventConstant.EventBizStep.COMMON_POINTS_CHANGED);
					bizEvent.setEventData(MapConverUtil.PO2Map(eventDate));
					// logger.info(bizEvent.toString());
					String returnString = eventService.sendEvent2MQ(bizEvent);

					logger.info("批量推送积分变更事件到MQ结束:" + returnString);

					logger.info("发送消息通知开始");
					MessageDto dto = new MessageDto();
					if (eventDate.getChangePoints() > 0) {
						// dto.setMessageContent("您的积分因为"+eventDate.getReason()+"+"+eventDate.getChangePoints()+",现有积分为："+eventDate.getAfterPoints()+"，请及时关注！");
						dto.setMessageContent(
								"您的积分因为手工调整，备注原因：" + eventDate.getReason() + "。+" + eventDate.getChangePoints()
										+ "分，当前积分：" + eventDate.getAfterPoints() + "分，详情请至个人中心-我的积分查看。");
					} else {
						// dto.setMessageContent("您的积分因为"+eventDate.getReason()+eventDate.getChangePoints()+",现有积分为："+eventDate.getAfterPoints()+"，请及时关注！");
						dto.setMessageContent(
								"您的积分因为手工调整，备注原因：" + eventDate.getReason() + "。" + eventDate.getChangePoints()
										+ "分，当前积分：" + eventDate.getAfterPoints() + "分，详情请至个人中心-我的积分查看。");
					}
					dto.setMessageTitle("积分变动");
					dto.setMessageType("40011005");
					dto.setUserId(potentialUserId);
					BizEvent et = new BizEvent();
					et.setEventBizType(EventBizType.SEND_MESSAGE);
					et.setEventBizStep(EventBizStep.SEND_MESSAGE_NOTICE);
					et.setEventKey("BATCH-CHANGE-MESSAGE-" + dto.getUserId() + ":" + new Date().getTime());
					et.setEventData(MapConverUtil.PO2Map(dto));
					String s = eventService.sendEvent2MQ(et);
					logger.info("批量发送消息通知结束，MQ返回结果>>>>>>>>>>>>>>>>>>>>" + s);
				}
			}
			result.put("flag", 1);
			result.put("msg", "批量消息推送成功");
			return result;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
	}

	public boolean queryDealer(String dealerCode) {
		boolean flag = false;
		try {
			List<TmDealer> list = tmDealerMapper.queryDealer(dealerCode);
			if (list.size() == 1) {
				flag = true;
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return flag;
	}

	public Map<String, Object> sendBirthday() {
		Map<String, Object> resultMap = new HashMap<>();
		String content = "尊敬的菱悦会会员，今天是您的生日，小菱诚挚的祝福您生日快乐！";
		// 查询出生日为当前日期的用户
		List<String> list = tmPotentialUserMapper.selectBirthday();
		logger.info("今天生日的用户数为：" + list.size());
		// 调用推送消息的接口
		if (list.size() != 0) {
			resultMap.put("errorCode", list.size());
			for (int i = 0; i < list.size(); i++) {
				sendMessage(list.get(i), content);
			}
		} else {
			logger.info("今日没有过生日的用户");
			resultMap.put("errorCode", "200");
			resultMap.put("errorMsg", "今日没有过生日的用户");
		}
		logger.info("返回结果>>>>>>>>>" + resultMap);
		return resultMap;
	}

	public static boolean notNull(String str) {
		return !(str == null || "".equals(str.trim()));
	}

	/**
	 * 查询库内已有车辆数据
	 * 
	 * @author Administrator TODO description
	 * @date 2017年11月14日
	 * @param vin
	 * @param engine
	 * @return
	 */
	public List<CarInfoDto> getCarInfo(String vin, String engine) {
		List<CarInfoDto> list = tmPotentialUserMapper.getCarInfo(vin, engine);
		return list;
	}

	/**
	 * PC后台潜客查询
	 * 
	 * @param queryMap
	 * @return
	 */
	public PageInfo<PotentialUserPO> queryPotentialList(Map<String, Object> queryMap) throws Exception {
		Page<PotentialUserPO> ss = PageHelper.startPage(Integer.parseInt(queryMap.get("pageNum").toString()),
				Integer.parseInt(queryMap.get("pageSize").toString()));
		logger.info("ss为————" + ss);
		List<PotentialUserPO> pd = tmPotentialUserMapper.queryPotentialList(queryMap);
		PageInfo<PotentialUserPO> page = new PageInfo<>(pd);
		logger.info("page为————" + page);
		return page;
	}

	/**
	 * PC后台潜客导出
	 * 
	 * @param queryMap
	 * @return
	 */
	public List<PotentialUserPO> exportPotentialListPC(Map<String, Object> queryMap) {
		List<PotentialUserPO> orderList = tmPotentialUserMapper.queryPotentialList(queryMap);
		logger.info("pd为————" + orderList.toString());
		return orderList;
	}

	/**
	 * PC后台车主查询
	 * 
	 * @param queryMap
	 * @return
	 */
	public PageInfo<CarOwnerPO> queryCarOwnerList(Map<String, Object> queryMap) {
		Page<CarOwnerPO> ss = PageHelper.startPage(Integer.parseInt(queryMap.get("pageNum").toString()),
				Integer.parseInt(queryMap.get("pageSize").toString()));
		logger.info("ss为————" + ss);
		List<CarOwnerPO> pd = tmPotentialUserMapper.queryCarOwnerList(queryMap);
		PageInfo<CarOwnerPO> page = new PageInfo<>(pd);
		logger.info("page为————" + page);
		return page;
	}

	/**
	 * PC后台车主导出
	 * 
	 * @param queryMap
	 * @return
	 */
	public List<CarOwnerPO> exportCarOwnerListPC(Map<String, Object> queryMap) {
		List<CarOwnerPO> orderList = tmPotentialUserMapper.queryCarOwnerList(queryMap);
		logger.info("pd为————" + orderList.toString());
		return orderList;
	}

	public String queryUserId(String openId) {
		String userId = tmPotentialUserMapper.queryUserId(openId).toString();
		return userId;
	}
	
	/**
	 * 重新获取关注信息
	 * @param openId
	 * @return
	 */
	public String getWXUserAgain(String openId) throws Exception {
		logger.info("获取的openId为："+openId);
//			Example example = new Example(TmPotentialUser.class);
//			Criteria criteria = example.createCriteria();
//			criteria.andCondition("DEVICE_OPEN_ID = ", openId);
		List<TmPotentialUser> tmPotentialUserList = tmPotentialUserMapper.queryPotentialUser(openId);
		if(tmPotentialUserList.isEmpty()){
			logger.info("用户关注失败，重新获取信息。");
			String url = CustomerInfoConstant.WECHAT_USER_URL;
			logger.info("重新获取信息URL:"+url);
			String accessToken = customerServiceInterface.genToken();
			//String accessToken = "_Vyfz9mG2md_Cp03WtEx73hM03d388bgNCwFLMaWHFA2siBwyCm1aaj8KO1G2mcy_lbh3MYBkox8hKomRdbvkJZfEfm7p84HHBDoK2j2chlAq7zQP3DQC-_-GgYruVEQITVgAIAWHJ";
			String token = "";
			JSONObject json = JSONObject.fromObject(accessToken);
            if (json == null || json.isNullObject()) {
                logger.info("返回结果为空");
            } else {
                token = json.getString("token");
                }
			logger.info("重新获取信息token:"+token);
			url = url.replace("ACCESS_TOKEN", token);
	        url = url.replace("OPENID", openId);
	        logger.info("替换过的重新获取信息URL:"+url);
	        String rsultStr = FrameHttpUtil.sendGet(url, null);
	        JSONObject data = JSONObject.fromObject(rsultStr);
            logger.info("返回结果为:"+data);
            if(data.getInt("subscribe")!=0){
            	Date newDate = new Date();
            	//SimpleDateFormat fromatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            	Date subscribeTime = new Date(data.getLong("subscribe_time"));
	            TmPotentialUser tmPotentialUser = new TmPotentialUser();
	            tmPotentialUser.setDeviceOpenId(openId);
	            tmPotentialUser.setSubscribeDate(subscribeTime);
	            tmPotentialUser.setSourceType(10011001);
	            tmPotentialUser.setStatus(10011001);
	            tmPotentialUser.setNickname(data.getString("nickname"));
	            tmPotentialUser.setSex(data.getString("sex"));
	            tmPotentialUser.setProvince(data.getString("province"));
	            tmPotentialUser.setCity(data.getString("city"));
	            tmPotentialUser.setCountry(data.getString("country"));
	            tmPotentialUser.setHeadImgurl(data.getString("headimgurl"));
	            tmPotentialUser.setCreateDate(newDate);
	            Integer result = tmPotentialUserMapper.insertSelective(tmPotentialUser);
	            logger.info("重新获取用户信息成功，插入条数："+result);
            }else{
            	logger.info("该用户已经取消关注， 不进行插入："+data.getInt("subscribe"));
            }
		}else{
			logger.info("该用户已存在");
		}
		return "200";
	}
}
